package com.dlc.shop.groupbuy.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.enums.EsOperationType;
import com.dlc.shop.bean.enums.OfflineHandleEventType;
import com.dlc.shop.bean.enums.SendType;
import com.dlc.shop.bean.event.EsProductUpdateEvent;
import com.dlc.shop.bean.event.SendMessageEvent;
import com.dlc.shop.bean.model.OfflineHandleEvent;
import com.dlc.shop.bean.param.NotifyTemplateParam;
import com.dlc.shop.bean.param.OfflineHandleEventAuditParam;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.groupbuy.common.dto.GroupActivityDto;
import com.dlc.shop.groupbuy.common.enums.ActivityStatusEnum;
import com.dlc.shop.groupbuy.common.enums.GroupActivityStatusEnum;
import com.dlc.shop.groupbuy.common.model.GroupActivity;
import com.dlc.shop.groupbuy.common.service.GroupActivityService;
import com.dlc.shop.security.platform.util.SecurityUtils;
import com.dlc.shop.service.OfflineHandleEventService;
import com.dlc.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author Yami
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/platform/group/activity")
@Tag(name = "平台端团购活动接口")
public class GroupActivityController {

    private final OfflineHandleEventService offlineHandleEventService;
    private final GroupActivityService groupActivityService;
    private final ProductService productService;
    private final ApplicationEventPublisher eventPublisher;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('group:activity:page')")
    @Operation(summary = "分页查找团购活动列表")
    public ServerResponseEntity<IPage<GroupActivityDto>> getGroupActivityPage(PageParam<GroupActivityDto> page, GroupActivityDto groupActivityDto) {
        groupActivityDto.setLang(I18nMessage.getDbLang());
        return ServerResponseEntity.success(groupActivityService.getGroupActivityPage(page, groupActivityDto));
    }

    @GetMapping("/info/{groupActivityId}")
    @PreAuthorize("@pms.hasPermission('group:activity:info')")
    @Operation(summary = "通过id查询团购活动")
    @Parameter(name = "groupActivityId", description = "团购活动id" , required = true)
    public ServerResponseEntity<GroupActivity> getById(@PathVariable("groupActivityId") Long groupActivityId) {
        return ServerResponseEntity.success(groupActivityService.getGroupActivityInfo(groupActivityId));
    }

    @DeleteMapping("/{groupActivityId}")
    @PreAuthorize("@pms.hasPermission('group:activity:delete')")
    @Operation(summary = "通过id删除拼团活动表")
    @Parameter(name = "groupActivityId", description = "团购活动id" , required = true)
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long groupActivityId) {
        // 查看活动是否为失效状态或者活动结束
        GroupActivity groupActivity = groupActivityService.getById(groupActivityId);
        if (Objects.isNull(groupActivity)) {
            // 未找到此活动，请稍后重试
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        // 如果活动状态不在 【未开始】、【已结束】、【已失效】、【违规下架】、【等待审核】的状态下无法进行删除操作
        boolean canDelete = !(Objects.equals(groupActivity.getActivityStatus(), ActivityStatusEnum.EXPIRED.value()) ||
                (groupActivity.getActivityStatus() >= 3 && groupActivity.getActivityStatus() <= 6));
        if (canDelete) {
            // 该活动状态下不能进行删除
            throw new YamiShopBindException("yami.activity.cannot.delete");
        }
        groupActivityService.updateToDelete(groupActivity);
        // 获取该活动下的所有商品
        productService.removeProdCacheByProdId(groupActivity.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(groupActivity.getProdId(), null, EsOperationType.UPDATE));
        groupActivityService.removeGroupActivityInfoCache(groupActivity.getProdId());
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/getOfflineHandleEventByActivityId/{activityId}")
    @PreAuthorize("@pms.hasPermission('group:activity:info')")
    @Operation(summary = "通过活动id获取下线信息")
    @Parameter(name = "activityId", description = "活动id" , required = true)
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByActivityId(@PathVariable("activityId") Long activityId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.GROUP_BUY.getValue(), activityId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('group:activity:update')")
    @Operation(summary = "下线活动")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        GroupActivity groupActivity = groupActivityService.getById(offlineHandleEvent.getHandleId());
        if (groupActivity == null) {
            // 未找到此活动，请稍后重试
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        if (Objects.equals(groupActivity.getStatus(),-1)) {
            //活动已被删除，请刷新页面重试
            throw new YamiShopBindException("yami.active.is.delete");
        }
        if (Objects.equals(groupActivity.getStatus(), GroupActivityStatusEnum.OFFLINE.value())) {
            //请勿重复下架活动
            throw new YamiShopBindException("yami.platform.prod.offline.check");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        groupActivityService.offline(groupActivity, offlineHandleEvent.getOfflineReason(), sysUserId);
        eventPublisher.publishEvent(new EsProductUpdateEvent(groupActivity.getProdId(), null, EsOperationType.UPDATE));
        //发送活动下架提醒给商家
        NotifyTemplateParam shopParam = new NotifyTemplateParam();
        shopParam.setShopId(groupActivity.getShopId());
        shopParam.setActivityId(groupActivity.getGroupActivityId());
        shopParam.setActivityName(groupActivity.getActivityName());
        shopParam.setSendType(SendType.ACTIVITY_OFFLINE.getValue());
        eventPublisher.publishEvent(new SendMessageEvent(shopParam));
        groupActivityService.removeGroupActivityInfoCache(groupActivity.getProdId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditGroupActivity")
    @PreAuthorize("@pms.hasPermission('group:activity:update')")
    @Operation(summary = "审核活动")
    public ServerResponseEntity<Void> auditGroupActivity(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        groupActivityService.auditGroupActivity(offlineHandleEventAuditParam, sysUserId);
        return ServerResponseEntity.success();
    }
}
